package com.molihub.controller;

import com.alibaba.fastjson.JSONObject;
import com.molihub.entity.RequestMessage;
import com.molihub.entity.User;
import com.molihub.utils.LogUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @ClassName: ChatController
 * @Description: 聊天控制器，处理聊天信息
 * @author: GGBOY
 * @date 2020/2/3 19:35
 * @Version: 1.0
 **/
@Controller
public class ChatController extends BaseController {

    private Logger logger = LogUtils.getInstance(ChatController.class);

    /**
     * 获取用户之间的聊天消息
     *
     * @param myName     我的用户名
     * @param friendName 好友用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/3
     */
    @ResponseBody
    @PostMapping("/chat/get/{myName}/{friendName}")
    public String sendChatMessage(@PathVariable String myName, @PathVariable String friendName) {
        logger.info("查询用户: " + myName + "和用户: " + friendName + "的聊天记录！");
        User my = userService.getUserByUserName(myName);
        User friend = userService.getUserByUserName(friendName);
        List<RequestMessage> messages = requestMessageService.findChatMessageById(my.getUserId(), friend.getUserId());
        return JSONObject.toJSONString(messages);
    }

    /**
     * 将该用户所有未读的聊天消息设为已读
     *
     * @param userName 用户名
     * @return void
     * @author GGBOY
     * @date 2020/2/4
     */
    @ResponseBody
    @GetMapping("/chat/read-all/{userName}")
    public String readAllChatMessage(@PathVariable String userName) {
        logger.info("将用户：" + userName +"的所有聊天通知设为已读！");
        User user = userService.getUserByUserName(userName);
        // 更新该用户ID所对应的所有未读消息状态变为已读
        requestMessageService.updateChatMessage(user.getUserId());
        return "ok";
    }
}
